<template>
  <div class="mainos">
    <div class="main_spac1" style="padding-bottom: 5px">
      <div class="main_white padding10">
        <el-form
          :inline="true"
          :rules="rules"
          :model="monitorForm"
          class="demo-form-inline marginTop0"
          ref="userListFrom"
          label-width="60px"
        >
          <div class="main_crumbs boxdq">
            <div class="main_crumbs_l">
              <a href="javascript:;" @click="$router.back(-1)">
                <i class="el-icon-arrow-down"></i>返回
              </a>
              <em>|</em>
              <span>审核报损报溢单</span>
            </div>
          </div>
          <div class="main_tile boxdq marginTop10">
            <div class="main_tile_l marginLeft0"><em></em>单据信息</div>
          </div>
          <div class="main_xq">
            <ul class="boxha">
              <li>
                单号：<span>{{ info.info.order_sn }}</span>
              </li>
              <li>
                单据类型：<span>{{ info.typeList[info.info.type] }}</span>
              </li>
              <li>
                创建时间：<span>{{
                  parseTime(info.info.created_at, "{y}-{m}-{d}")
                }}</span>
              </li>
              <li class="main_w100 box">
                备注：
                <div class="box main_xqi" style="margin-top: -4px">
                  <el-input
                    v-model.trim="monitorForm.form.remark"
                    placeholder="备注"
                    clearable
                    style="width: 100%"
                    @change="isEdit = true"
                  ></el-input>
                </div>
              </li>
            </ul>
          </div>
          <div class="main_tile boxdq marginTop15">
            <div class="main_tile_l marginLeft0"><em></em>商品详情</div>
          </div>
          <div class="main_white padding10 marginBottom10">
            <div class="main_white">
              <div class="boxdq boxha">
                <div class="mainor_sp boxdq">
                  <div class="box">
                    <ul class="box">
                      <li class="box">
                        <span> <em>*</em>商品名称： </span>
                        <el-autocomplete
                          v-model="formsp.value"
                          ref="searchSelect"
                          class="wid240 main_comm"
                          @clear="$refs.searchSelect.$children[0].blur()"
                          :fetch-suggestions="
                            (queryString, cb) => {
                              querySearchAsync(queryString, cb);
                            }
                          "
                          placeholder="商品名称/别名/编码/助记码"
                          clearable
                          :highlight-first-item="true"
                          value-key="name"
                          @select="
                            (item) => {
                              handleSelect(item);
                            }
                          "
                        >
                          <template slot-scope="{ item }">
                            <div class="main_name">
                              <span>
                                {{ item.goods.name }}【{{
                                  item.spu_name ? item.spu_name.title : ""
                                }}】
                              </span>
                              <span class="code">{{
                                item.goods_spu_code
                              }}</span>
                            </div>
                          </template>
                        </el-autocomplete>
                      </li>
                      <li class="box">
                        <span> <em>*</em>数量： </span>
                        <el-input
                          v-model.trim="formsp.num"
                          ref="focusw2"
                          placeholder="数量"
                          clearable
                          class="wid140"
                          @keyup.enter.native="mainor_sp"
                        ></el-input>
                      </li>
                    </ul>
                    <div class="marginBottom10">
                      <el-button type="primary" @click="mainor_qr"
                        >确认(回车)</el-button
                      >
                      <el-button
                        class="reset marginLeft5"
                        type="info"
                        @click="reset"
                        >重置</el-button
                      >
                    </div>
                  </div>
                </div>
              </div>
              <div class="main_table marginTop0">
                <el-table
                  ref="multipleTable"
                  :data="monitorForm.list"
                  element-loading-text="加载中"
                  fit
                  border
                  highlight-current-row
                >
                  <el-table-column label="序号" width="80">
                    <template slot-scope="scope">{{
                      scope.$index + 1
                    }}</template>
                  </el-table-column>
                  <el-table-column
                    label="商品名称"
                    prop="name"
                    show-overflow-tooltip
                    min-width="150"
                  >
                    <template slot-scope="scope"
                      ><div v-if="scope.row.show">
                        {{ scope.row.goods.name }}【{{
                          scope.row.goods_spu.spu_name.title
                        }}】
                      </div>
                      <div v-else>
                        {{ scope.row.name }}【{{ scope.row.spu_name }}】
                      </div></template
                    >
                  </el-table-column>
                  <el-table-column label="单位" prop="goods_spu.spu_unit.title">
                    <template slot-scope="scope"
                      ><div v-if="scope.row.show">
                        {{ scope.row.goods_spu.spu_unit.title }}
                      </div>
                      <div v-else>{{ scope.row.unit }}</div></template
                    >
                  </el-table-column>
                  <el-table-column label="原系统库存">
                    <template slot-scope="scope">
                      <span :class="[scope.row.red ? 'isred' : '']">{{
                        scope.row.inventory_num
                      }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="实时库存" prop="price">
                    <template slot-scope="scope"
                      ><div v-if="scope.row.show">
                        {{ scope.row.goods_spu.inventory.num }}
                      </div>
                      <div v-else>{{ scope.row.inventory_num }}</div></template
                    >
                  </el-table-column>
                  <el-table-column
                    label="数量"
                    prop="num"
                    min-width="150"
                    class-name="main_hei"
                  >
                    <template slot-scope="scope">
                      <el-form-item
                        :prop="'list.' + scope.$index + '.num'"
                        :rules="rules.num"
                        label-width="10px"
                        label=" "
                      >
                        <el-input
                          v-model.trim="scope.row.num"
                          :ref="'num' + scope.row.goods_spu_id"
                          @input="scope.row.xs = false"
                          @change="numberChange($event, scope.$index)"
                          placeholder="数量"
                          class="wid110"
                        ></el-input>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column label="库存价" prop="price" />
                  <el-table-column label="金额" prop="price">
                    <template slot-scope="scope">{{
                      parseFloat(scope.row.num) * parseFloat(scope.row.price)
                        ? $toFixed(
                            parseFloat(scope.row.num) *
                              parseFloat(scope.row.price)
                          )
                        : 0
                    }}</template>
                  </el-table-column>
                  <el-table-column
                    label="备注"
                    prop="remark"
                    width="350"
                    class-name="main_hei"
                  >
                    <template slot-scope="scope">
                      <el-form-item label-width="0" label="">
                        <el-input
                          v-model.trim="scope.row.remark"
                          placeholder="备注"
                          class="wid240"
                        ></el-input>
                      </el-form-item>
                      <el-link
                        type="danger"
                        @click="
                          scope.row.show
                            ? lengt <= 1
                              ? endDelete()
                              : scdelete(scope.$index, true)
                            : scdelete(scope.$index)
                        "
                        class="paddingTop20"
                        >删除</el-link
                      >
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </div>
          <div class="newConBox_p200 paddingBottom10" id="newConBox">
            <div class="newConBox_h32">
              <div
                :class="['mainor_pr boxdq newConBox ', { on: searchBarFixed }]"
              >
                <div class="mainor_prl">
                  <el-button
                    type="primary"
                    @click="preservation(0)"
                    v-repeatClick
                    >保存</el-button
                  >
                  <el-button
                    class="reset marginLeft10"
                    type="info"
                    @click="preservation(1), (isEdit = false)"
                    v-repeatClick
                    >保存并审核</el-button
                  >
                  <el-button
                    class="marginLeft10"
                    @click="preservation(2), (isEdit = false)"
                    v-repeatClick
                    >取消报损报溢单</el-button
                  >
                  <el-button @click="$router.back(-1), (isEdit = false)"
                    >取消</el-button
                  >
                </div>
                <div class="mainor_prr">
                  <span>合计：¥{{ total }}</span>
                </div>
              </div>
            </div>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
const shuju = {
  list: {
    id: "",
    name: "",
    goods_id: "",
    goods_spu_id: "",
    spu_name: "",
    unit: "",
    inventory_num: "",
    price: "",
    num: "",
    remark: "",
    show: false,
  },
  form: {
    remark: "",
  },
  formsp: {
    name: [],
    girard: null,
    num: "",
    value: "",
  },
  isEdit: false,
};
import {
  reportedSpills_info,
  reportedSpills_checkGoods,
  reportedSpills_check,
  reportedSpills_deleteList,
} from "@/api/warehouse/warehouseLoss";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";
import rules from "@/rules/warehouse/warehouseLoss_add";
import { parseTime } from "@/utils/index";
import { goods_getGoodsSpu } from "@/api/currency";

export default {
  computed: {
    total() {
      let sz = 0;
      this.monitorForm.list.forEach((e) => {
        sz += parseFloat(e.num * e.price);
      });
      return this.$toFixed(sz);
    },
    lengt() {
      let zj = 0;
      this.monitorForm.list.map((e) => {
        if (e.show) {
          zj++;
        }
      });
      return zj;
    },
  },
  components: {},
  data() {
    return {
      // 验证
      rules,
      // 时间
      parseTime,
      // 基本信息
      info: {
        info: {
          created_at: "2000-01-01",
          reportedSpills_time: "2000-01-01",
          reported_spills_list: [],
        },
        statusList: ["待审核"],
        typeList: ["待审核"],
      },
      listLoading: false,
      // 列表数据
      monitorForm: {
        form: {
          remark: "",
        },
        list: [],
      },
      // 商品搜索
      formsp: {
        name: [],
        girard: null,
        num: "",
        value: "",
      },
      deleteIds: [],
      inventory_num: "",
      price: "",
      show: true,
      // id
      id: this.$route.params.id,
      // 监听滚动
      searchBarFixed: false,
    };
  },
  mounted() {
    window.addEventListener("scroll", this.handleScroll);
  },
  destroyed() {
    window.removeEventListener("scroll", this.handleScroll);
  },
  created() {
    // 基本信息
    this.reportedSpills_info();
  },
  beforeRouteLeave(to, from, next) {
    if (this.isEdit) {
      setTimeout(() => {
        this.$confirm(
          "您已经有数据操作，离开页面系统不会保存您的操作，确定离开吗？",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(() => {
            // 正常跳转
            next();
          })
          .catch(() => {
            next(false);
          });
      }, 200);
    } else {
      next();
    }
  },
  methods: {
    // 监听滚动
    handleScroll() {
      let scrollTop =
        window.pageYOffset ||
        document.documentElement.scrollTop ||
        document.body.scrollTop;
      scrollTop + document.documentElement.clientHeight >
      document.getElementById("newConBox").offsetTop + 300
        ? (this.searchBarFixed = false)
        : (this.searchBarFixed = true);
    },
    // 商品搜索
    querySearchAsync(queryString, cb) {
      if (queryString.trim() == "") {
        cb([]);
        return;
      }
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(
              Object.assign(apiUrl().name, { name: queryString.trim() })
            ) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { name: queryString.trim() }
      );
      goods_getGoodsSpu(data).then((res) => {
        if (res.errcode == 0) {
          res.data.goods.map((e) => {
            e.name = e.goods.name + "【" + e.spu_unit.title + "】";
          });
          var results = res.data.goods;
          if (this.$refs.searchSelect) {
            this.$refs.searchSelect.activated = true;
          }
          cb(results);
        } else {
          this.$message.error(res.errmsg);
          cb([]);
        }
      });
    },
    // 商品选择
    handleSelect(item) {
      this.formsp.name = item;
      this.formsp.girard = item.id;
      this.reportedSpills_checkGoods();
    },
    reportedSpills_checkGoods() {
      let formsp = JSON.parse(JSON.stringify(this.formsp));
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(
              Object.assign(apiUrl().name, {
                goods_id: formsp.name.goods_id,
                goods_spu_id: formsp.girard,
              })
            ) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        {
          goods_id: formsp.name.goods_id,
          goods_spu_id: formsp.girard,
        }
      );
      reportedSpills_checkGoods(data).then((res) => {
        if (res.errcode == 0) {
          this.inventory_num = res.data.num;
          this.price = res.data.price;
          setTimeout(() => {
            this.$refs.focusw2.focus();
          }, 100);
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 商品选择确认(回车)
    mainor_sp(e) {
      var keyCode = window.event ? e.keyCode : e.which;
      if (keyCode == 13) {
        this.mainor_qr();
      }
    },
    // 点击添加
    mainor_qr() {
      this.isEdit = true;
      let formsp = JSON.parse(JSON.stringify(this.formsp));
      if (!formsp.name.name) {
        this.$message.error("请填写商品名称");
        this.$refs.searchSelect.focus();
        return;
      } else if (formsp.num == "") {
        this.$message.error("请填写数量");
        this.$refs.focusw2.focus();
        return;
      } else {
        let monitorForm_list = JSON.parse(
          JSON.stringify(this.monitorForm.list)
        );
        let ind = 0;
        if (monitorForm_list.length != 0) {
          monitorForm_list.map((e, index) => {
            if (e.goods_spu_id == formsp.girard) {
              ind = e.goods_spu_id;
              return;
            }
          });
          if (ind == 0) {
            this.handle(formsp);
          } else {
            setTimeout(() => {
              this.$refs["num" + ind].focus();
              this.reset();
              ind = 0;
            }, 100);
          }
        } else {
          this.handle(formsp);
        }
      }
    },
    handle(formsp) {
      let list = JSON.parse(JSON.stringify(shuju.list));
      list.name = formsp.name.goods.name;
      list.goods_id = formsp.name.goods_id;
      list.goods_spu_id = formsp.name.id;
      list.spu_name = formsp.name.spu_name.title;
      list.unit = formsp.name.spu_unit.title;
      list.price = this.price;
      list.inventory_num = this.inventory_num;
      list.num = formsp.num;
      list.remark = formsp.name.remark;
      this.monitorForm.list.push(list);
      this.reset();
      setTimeout(() => {
        this.$refs.searchSelect.focus();
      }, 100);
    },
    reset() {
      this.formsp = JSON.parse(JSON.stringify(shuju.formsp));
      this.show = false;
      this.$nextTick(() => {
        this.show = true;
      });
    },
    numberChange(val, index) {
      this.monitorForm.list.map((e) => {
        if (e.show) {
          e.new_inventory_num = e.goods_spu.inventory.num;
        } else {
          e.new_inventory_num = e.inventory_num;
        }
      });
      if (this.info.info.type == 2 || this.info.info.type == 4) {
        this.monitorForm.list[index].num = parseFloat(val);
        return;
      }
      if (
        parseFloat(val) <=
        parseFloat(this.monitorForm.list[index].new_inventory_num)
      ) {
        this.monitorForm.list[index].num = parseFloat(val);
      } else {
        this.monitorForm.list[index].num = parseFloat(
          this.monitorForm.list[index].new_inventory_num
        );
      }
    },
    // 删除
    scdelete(index, type) {
      if (type) {
        this.deleteIds.push(this.monitorForm.list[index].id);
        this.monitorForm.list.splice(index, 1);
        // let data = Object.assign(
        //   {
        //     sign: Md5(
        //       objKeySort(
        //         Object.assign(apiUrl().name, {
        //           id: this.monitorForm.list[index].id,
        //         })
        //       ) + apiUrl().appsecret
        //     ),
        //   },
        //   apiUrl().name,
        //   { id: this.monitorForm.list[index].id }
        // );
        // reportedSpills_deleteList(data).then((res) => {
        //   if (res.errcode == 0) {
        //     this.monitorForm.list.splice(index, 1);
        //   } else {
        //     this.$message.error(res.errmsg);
        //   }
        // });
      } else {
        this.deleteIds.push(this.monitorForm.list[index].id);
        this.monitorForm.list.splice(index, 1);
      }
    },
    endDelete() {
      this.$message.error("订单最后一个商品无法删除");
    },
    // 保存
    preservation(type) {
      this.$refs["userListFrom"].validate((valid) => {
        if (valid) {
          if (type == 1) {
            let arr = this.monitorForm.list.filter((e) => {
              if (
                parseFloat(e.inventory_num) !=
                parseFloat(e.goods_spu.inventory.num)
              ) {
                return e;
              }
            });
            let message = "保存并审核通过报损报溢单?";
            if (arr.length > 0) {
              message = `存在【${arr.length}】个商品，原系统库存和实时库存存在差异，继续保存并通过报损报溢单？`;
            }
            this.$confirm(message, "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            })
              .then(() => {
                this.reportedSpills_check(type);
              })
              .catch(() => {});
          } else if (type == 2) {
            this.$confirm("确定关闭报损报溢单?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            })
              .then(() => {
                this.reportedSpills_check(type);
              })
              .catch(() => {});
          } else {
            this.reportedSpills_check(type);
          }
        }
      });
    },
    reportedSpills_check(type) {
      let arry = [];
      let monitorForm = JSON.parse(JSON.stringify(this.monitorForm));
      monitorForm.list.map((e) => {
        arry.push({
          id: e.id ? e.id : null,
          goods_id: e.goods_id,
          goods_spu_id: e.goods_spu_id,
          remark: e.remark,
          num: e.num,
          price: e.price,
        });
      });
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(
              Object.assign(apiUrl().name, { id: this.id, status: type })
            ) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        monitorForm.form,
        { delete_ids: this.deleteIds.join(",") },
        {
          list: JSON.stringify(arry),
          id: this.id,
          status: type,
        }
      );
      reportedSpills_check(data).then((res) => {
        if (res.errcode == 0) {
          this.$message({
            message: "保存成功",
            type: "success",
          });
          this.$router.go(-1);
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 基本信息
    reportedSpills_info() {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, { id: this.id })) +
              apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { id: this.id }
      );
      reportedSpills_info(data).then((res) => {
        if (res.errcode == 0) {
          res.data.info.reported_spills_list.map((e) => {
            e.show = true;
            e.red = false;
            if (
              parseFloat(e.inventory_num) !=
              parseFloat(e.goods_spu.inventory.num)
            ) {
              e.red = true;
            }
          });
          this.monitorForm.list = res.data.info.reported_spills_list;

          this.monitorForm.form.remark = res.data.info.remark;
          this.info = res.data;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
@import "@/styles/variables.scss";

.mainos {
  .main_tile {
    .mainos_tile_r {
      color: $colour_red;
      font-size: $font_14;
    }
  }
  .newConBox.on {
    margin-left: -10px;
  }
  .main_table {
    /deep/.el-table--small td {
      padding-top: 0;
    }
    /deep/.el-form-item--small.el-form-item {
      margin-bottom: 16px;
      margin-top: 16px;
      margin-right: 0;
    }
  }
  .mainor_pr {
    margin-left: 10px;
    margin-bottom: 10px;
    /deep/.el-button--default {
      border-color: $subActive;
      color: $menuText;
      &:hover {
        border-color: $menuActiveText;
        color: $menuActiveText;
      }
    }
    .mainor_prr {
      font-size: $font_16;
      color: $colour_18;
      span {
        color: #fe3b3b;
        margin-left: 10px;
      }
    }
  }
  .main_xq {
    ul {
      li {
        .main_xqi {
          width: 80%;
          margin-left: 5px;
        }
        .main_upImg {
          /deep/ul {
            li {
              padding-left: 0;
            }
          }
          /deep/.el-upload-list--picture-card
            .el-upload-list__item:first-child {
            margin-left: 145px;
          }
        }
      }
    }
  }
  .mainor_sp {
    ul {
      margin-right: 20px;
      li {
        margin-bottom: 10px;
        & > span {
          display: inline-block;
          line-height: 32px;
          width: 60px;
          color: $colour_18;
          font-size: $font_14;
          text-align: right;
          em {
            color: $colour_red;
            margin-right: 5px;
          }
        }
        &:first-child {
          & > span {
            width: 85px;
          }
        }
      }
    }
  }
  .base_p {
    width: 80px;
  }
  .main_page_top {
    margin-top: 7px;
    margin-left: 10px;
    use {
      fill: $menuText;
    }
    &:hover {
      cursor: pointer;
      use {
        fill: $menuActiveText;
      }
    }
  }
}
.main_name {
  display: flex;
  flex-direction: column;
  line-height: initial;
  padding: 8px 0;
  .code {
    color: #999;
  }
}
.isred {
  color: red;
  font-weight: 700;
}
</style>
